'use client'

import Head from 'next/head'
import Script from 'next/script'

export default () => {
    return  (<div>
    <Head>
      <title>My page title</title>
      <meta http-equiv="Content - Security - Policy" content="style - src 'unsafe - inline'" />
      <meta name="viewport" content="initial-scale=1.0, width=device-width" key="viewport" />
    </Head>
    <div className='content'>
      {/* <canvas className="new-canvas" id="blend-canvas"></canvas> */}
    </div>
  
   <style jsx>{`
      .content {
        flex-direction: column;
        align-items: center;
        width: 100%;
      }
      // .new-canvas {
      //   height: 380px;
      //   width: 380px;
      // }
    `}
  </style>

  <Script
  id="show-banner"
  dangerouslySetInnerHTML={{
    __html: ` 
    {
      /**
       * @param {number} x
       * @param {number} y
       * @return {?}
       */
       function createCanvas(x, y) {
        /** @type {Element} */
        var r = document.createElement("canvas");
        return r.width = x, r.height = y, r;
      }
      
      /**
       * @param {WebGLRenderingContext} ctx
       * @param {?} n
       * @param {string} string
       * @return {?}
       */
        function createShaderFromSource(ctx, n, string) {
          var id = ctx.createShader(n);
          if (ctx.shaderSource(id, string), ctx.compileShader(id), ctx.getShaderParameter(id, ctx.COMPILE_STATUS)) {
            return id;
          }
          console.log(ctx.getShaderInfoLog(id));
          ctx.deleteShader(id);
        }
        /**
         * @param {WebGLRenderingContext} gl
         * @param {?} vertexShader
         * @param {?} shader
         * @return {?}
         */
        function createProgramFromShader(gl, vertexShader, shader) {
          var program = gl.createProgram();
          if (gl.attachShader(program, vertexShader), gl.attachShader(program, shader), gl.linkProgram(program), gl.getProgramParameter(program, gl.LINK_STATUS)) {
            return program;
          }
          console.error(gl.getProgramInfoLog(program));
          gl.deleteProgram(program);
        }
        /**
         * @param {Object} gl
         * @param {?} value
         * @return {?}
         */
        function createTextureFromCanvas(gl, value) {
          var texture = gl.createTexture();
          return gl.bindTexture(gl.TEXTURE_2D, texture), 
          gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, value), 
          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR), 
          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR), 
          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE), 
          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE), 
          texture;
        }

        function createTextureFromImage(gl, value, width, height) {
          var texture = gl.createTexture();
          return gl.bindTexture(gl.TEXTURE_2D, texture), 
          gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, value),
          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR), 
          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR), 
          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE), 
          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE), 
          texture;
        }

        /** @type {Array} */
        var m = [1, 1, 1, -1, -1, 1, -1, -1];
        /**
         * @param {number} a
         * @param {number} g
         * @return {?}
         */
        function UVSize(a, g) {
          return Math.min(a, g) / 501 * 1.1;
        }
        
        function blendImage(width, height, imageCanvas, maskCanvas) {
            var canvas;
            var webglCanvas;
            var gl;
            var size;
            var vs;
            var hfs;
            var vfs;
            var cutoffShader;
            var blurShader;
            var motionBlurXProgram;
            var motionBlurYProgram;
            var cutoffProgram;
            var blurProgram;
            var imageTexture;
            var maskTexture;
            var elementBuffer;
            var blurredMaskTexture;
            var blurredAlpha;
            var blurredFA;
            var blurredB1A;
            var result;
            var ctx;
            gl = (webglCanvas = createCanvas(width, height, {})).getContext("webgl")
            if(!gl) return;
            gl.viewport(0, 0, width, height);
            size = UVSize(width, height);
            // size = 0.1;
            vs = createShaderFromSource(gl, gl.VERTEX_SHADER, \`
                    precision highp float;
                    attribute vec4 position;
                    attribute vec4 inputTextureCoordinate;
                    varying vec2 textureCoordinate;        
                    void main() {            
                      gl_Position = position;            
                      textureCoordinate = vec2((position.x+1.0)/2.0, 1.0-(position.y+1.0)/2.0);        
                    }\`);
            hfs = createShaderFromSource(gl, gl.FRAGMENT_SHADER, \`
            precision mediump float;    
            varying vec2 textureCoordinate;    
            uniform sampler2D texture;    
            uniform float textureWidth;    
            uniform float textureHeight;    
            uniform float size;    
            const int  radius = 8;    
            // const int kernelSize = 40;    
            void main()    {                        
              vec4 sum            = vec4(0.0);        
              vec4 result         = vec4(0.0);        
              vec2 unit_uv        = vec2(size / textureWidth,size / textureHeight)*1.0;        
              vec4 curColor       = texture2D(texture, textureCoordinate);        
              vec4 centerPixel    = curColor;                
              float sum_weight    = 1.0;        
              //horizontal        
              for(int i=-radius;i<=radius;i++)        {            
                vec2 curRightCoordinate = textureCoordinate+vec2(float(i),0.0)*unit_uv;            
                vec2 curLeftCoordinate  = textureCoordinate-vec2(float(i),0.0)*unit_uv;            
                sum += texture2D(texture,curRightCoordinate);            
                sum += texture2D(texture,curLeftCoordinate);            
                sum_weight+=2.0;        
              }                
              result = (sum+centerPixel)/sum_weight;
              gl_FragColor = result;
            }\`);
            vfs = createShaderFromSource(gl, gl.FRAGMENT_SHADER, \`
            precision mediump float;    
            varying vec2 textureCoordinate;    
            uniform sampler2D texture;    
            uniform float textureWidth;    
            uniform float textureHeight;    
            const int  radius = 8;    
            uniform float size;    
            void main()    {         
              vec4 sum            = vec4(0.0);        
              vec4 result         = vec4(0.0);        
              vec2 unit_uv        = vec2(size / textureWidth,size / textureHeight)*1.0;        
              vec4 centerPixel    = texture2D(texture, textureCoordinate);        
              float  sum_weight   = 1.0;                
              //vertical        
              for(int i=-radius;i<=radius;i++)        {            
                vec2 curBottomCoordinate    = textureCoordinate+vec2(0.0,float(i))*unit_uv;            
                vec2 curTopCoordinate       = textureCoordinate+vec2(0.0,float(i))*unit_uv; 
                sum += texture2D(texture,curBottomCoordinate);
                sum += texture2D(texture,curTopCoordinate);            
                sum_weight+=2.0;        
              }
              sum+=centerPixel;
              result = vec4(sum.rgb/sum_weight,sum.a/sum_weight);
              gl_FragColor = result;
            }\`);
            cutoffShader = createShaderFromSource(gl, gl.FRAGMENT_SHADER, \`
            precision mediump float;    
            uniform sampler2D texture1;    
            uniform sampler2D texture2;    
            uniform int type;    
            varying vec2 textureCoordinate;    
            void main()    {           
              vec4 color1 = texture2D(texture1, textureCoordinate);
              vec4 color2 = texture2D(texture2, textureCoordinate);                
                  if (type == 1) {            
                    gl_FragColor = mix(vec4(0.0,0.0,0.0,1.0), color1, color2.a);
                  } else if (type == 2) {            
                    // todo:            
                    // gl_FragColor = color1 / color2;        
                  } else if (type == 3) {            
                    gl_FragColor = mix(vec4(0.0,0.0,0.0,1.0), color1, 1.0-color2.a);
                  }      
                }\`);
            blurShader = createShaderFromSource(gl, gl.FRAGMENT_SHADER, \`
            precision highp float;         
            uniform sampler2D texture;         
            uniform sampler2D maskTexture;         
            uniform sampler2D blurred_alpha;         
            uniform sampler2D blurred_FA;         
            uniform sampler2D blurred_B1A;         
            varying vec2 textureCoordinate;         
            void main()         {              
              vec4 srcImage = texture2D(texture, textureCoordinate);              
              vec4 maskImage = texture2D(maskTexture, textureCoordinate);              
              float alpha = maskImage.a;              
              float blurredAlpha = texture2D(blurred_alpha, textureCoordinate).a;            
              vec4 blurredFALoad = texture2D(blurred_FA, textureCoordinate);              
              vec3 blurredFA = blurredFALoad.rgb;
              vec3 blurredF = blurredFA / (blurredAlpha + 0.0001);              
              vec4 blurredB1ALoad = texture2D(blurred_B1A, textureCoordinate);             
              vec3 blurredB1A = blurredB1ALoad.rgb;    
              vec3 blurredB = blurredB1A * blurredB1ALoad.a / (1.0 - blurredAlpha + 0.0001);              
              vec3 tmp = srcImage.rgb + blurredF * (-alpha) + blurredB * (alpha-1.0);              
              vec3 fore = blurredF + tmp * (alpha);              
              gl_FragColor = vec4(fore * srcImage.a * maskImage.a, srcImage.a * maskImage.a);
            }\`);
            motionBlurXProgram = createProgramFromShader(gl, vs, hfs);
            motionBlurYProgram = createProgramFromShader(gl, vs, vfs);
            cutoffProgram = createProgramFromShader(gl, vs, cutoffShader);
            blurProgram = createProgramFromShader(gl, vs, blurShader); 
            imageTexture = createTextureFromCanvas(gl, imageCanvas, width, height);
            maskTexture = createTextureFromCanvas(gl, maskCanvas, width, height);
            elementBuffer = gl.createBuffer();
            gl.bindBuffer(gl.ARRAY_BUFFER, elementBuffer);
            gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(m),gl.STATIC_DRAW);
      
            gl.useProgram(motionBlurXProgram); 
            gl.enableVertexAttribArray(gl.getAttribLocation(motionBlurXProgram, "position"));
            gl.vertexAttribPointer(gl.getAttribLocation(motionBlurXProgram, "position"), 2, gl.FLOAT, false, 0, 0);
            gl.activeTexture(gl.TEXTURE0);
            gl.bindTexture(gl.TEXTURE_2D, maskTexture);
            gl.uniform1i(gl.getUniformLocation(motionBlurXProgram, "texture"), 0);
            gl.uniform1fv(gl.getUniformLocation(motionBlurXProgram, "textureWidth"), [width]);
            gl.uniform1fv(gl.getUniformLocation(motionBlurXProgram, "textureHeight"), [height]);
            gl.uniform1fv(gl.getUniformLocation(motionBlurXProgram, "size"), [size]);
            gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
            blurredMaskTexture = createTextureFromCanvas(gl, webglCanvas);
      
            gl.useProgram(motionBlurYProgram);
            gl.enableVertexAttribArray(gl.getAttribLocation(motionBlurYProgram,"position"));
            gl.vertexAttribPointer(gl.getAttribLocation(motionBlurYProgram, "position"), 2, gl.FLOAT, false, 0, 0);
            gl.activeTexture(gl.TEXTURE0);
            gl.bindTexture(gl.TEXTURE_2D, blurredMaskTexture);
            gl.uniform1i(gl.getUniformLocation(motionBlurYProgram, "texture"), 0);
            gl.uniform1fv(gl.getUniformLocation(motionBlurYProgram, "textureWidth"), [width]);
            gl.uniform1fv(gl.getUniformLocation(motionBlurYProgram, "textureHeight"), [height]); 
            gl.uniform1fv(gl.getUniformLocation(motionBlurYProgram, "size"), [size]);
            gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
            blurredAlpha = createTextureFromCanvas(gl, webglCanvas);
            gl.deleteTexture(blurredMaskTexture);
            
            gl.useProgram(cutoffProgram);
            gl.enableVertexAttribArray(gl.getAttribLocation(cutoffProgram, "position")); 
            gl.vertexAttribPointer(gl.getAttribLocation(cutoffProgram, "position"), 2, gl.FLOAT, false, 0, 0);
            gl.activeTexture(gl.TEXTURE0);
            gl.bindTexture(gl.TEXTURE_2D, imageTexture);
            gl.uniform1i(gl.getUniformLocation(cutoffProgram, "texture1"), 0);
            gl.activeTexture(gl.TEXTURE1);
            gl.bindTexture(gl.TEXTURE_2D, maskTexture); 
            gl.uniform1i(gl.getUniformLocation(cutoffProgram, "texture2"), 1);
            gl.uniform1iv(gl.getUniformLocation(cutoffProgram, "type"), [1]);
            gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
            blurredFA = createTextureFromCanvas(gl, webglCanvas);
      
            gl.useProgram(motionBlurXProgram);
            gl.enableVertexAttribArray(gl.getAttribLocation(motionBlurXProgram, "position"));
            gl.vertexAttribPointer(gl.getAttribLocation(motionBlurXProgram, "position"), 2, gl.FLOAT, false, 0, 0);
            gl.activeTexture(gl.TEXTURE0);
            gl.bindTexture(gl.TEXTURE_2D, blurredFA);
            gl.uniform1i(gl.getUniformLocation(motionBlurXProgram, "texture"), 0);
            gl.uniform1fv(gl.getUniformLocation(motionBlurXProgram, "textureWidth"), [width]);
            gl.uniform1fv(gl.getUniformLocation(motionBlurXProgram, "textureHeight"), [height]);
            gl.uniform1fv(gl.getUniformLocation(motionBlurXProgram, "size"), [size]);
            gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
            blurredMaskTexture = createTextureFromCanvas(gl, webglCanvas);
            gl.deleteTexture(blurredFA);
      
            gl.useProgram(motionBlurYProgram);
            gl.enableVertexAttribArray(gl.getAttribLocation(motionBlurYProgram, "position"));
            gl.vertexAttribPointer(gl.getAttribLocation(motionBlurYProgram, "position"), 2, gl.FLOAT, false, 0, 0);
            gl.activeTexture(gl.TEXTURE0);
            gl.bindTexture(gl.TEXTURE_2D, blurredMaskTexture);
            gl.uniform1i(gl.getUniformLocation(motionBlurYProgram, "texture"), 0);
            gl.uniform1fv(gl.getUniformLocation(motionBlurYProgram, "textureWidth"), [width]);
            gl.uniform1fv(gl.getUniformLocation(motionBlurYProgram, "textureHeight"), [height]); 
            gl.uniform1fv(gl.getUniformLocation(motionBlurYProgram, "size"), [size]);
            gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
            blurredFA = createTextureFromCanvas(gl, webglCanvas); 
            gl.deleteTexture(blurredMaskTexture);
      
            gl.useProgram(cutoffProgram); 
            gl.enableVertexAttribArray(gl.getAttribLocation(cutoffProgram, "position"));
            gl.vertexAttribPointer(gl.getAttribLocation(cutoffProgram,"position"), 2, gl.FLOAT, false, 0, 0);
            gl.activeTexture(gl.TEXTURE0);
            gl.bindTexture(gl.TEXTURE_2D, imageTexture);
            gl.uniform1i(gl.getUniformLocation(cutoffProgram, "texture1"), 0);
            gl.activeTexture(gl.TEXTURE1);
            gl.bindTexture(gl.TEXTURE_2D, maskTexture);
            gl.uniform1i(gl.getUniformLocation(cutoffProgram, "texture2"), 1); 
            gl.uniform1iv(gl.getUniformLocation(cutoffProgram, "type"), [3]);
            gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
            blurredB1A = createTextureFromCanvas(gl, webglCanvas);
      
            gl.useProgram(motionBlurXProgram);
            gl.enableVertexAttribArray(gl.getAttribLocation(motionBlurXProgram, "position"));
            gl.vertexAttribPointer(gl.getAttribLocation(motionBlurXProgram, "position"), 2, gl.FLOAT, false, 0, 0); 
            gl.activeTexture(gl.TEXTURE0);
            gl.bindTexture(gl.TEXTURE_2D, blurredB1A);
            gl.uniform1i(gl.getUniformLocation(motionBlurXProgram, "texture"), 0);
            gl.uniform1fv(gl.getUniformLocation(motionBlurXProgram, "textureWidth"), [width]);
            gl.uniform1fv(gl.getUniformLocation(motionBlurXProgram, "textureHeight"), [height]); 
            gl.uniform1fv(gl.getUniformLocation(motionBlurXProgram, "size"), [size]);
            gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
            blurredMaskTexture = createTextureFromCanvas(gl, webglCanvas);
            gl.deleteTexture(blurredB1A);
            
            gl.useProgram(motionBlurYProgram);
            gl.enableVertexAttribArray(gl.getAttribLocation(motionBlurYProgram, "position"));
            gl.vertexAttribPointer(gl.getAttribLocation(motionBlurYProgram, "position"), 2, gl.FLOAT, false, 0, 0);
            gl.activeTexture(gl.TEXTURE0);
            gl.bindTexture(gl.TEXTURE_2D, blurredMaskTexture);
            gl.uniform1i(gl.getUniformLocation(motionBlurYProgram, "texture"), 0);
            gl.uniform1fv(gl.getUniformLocation(motionBlurYProgram, "textureWidth"), [width]);
            gl.uniform1fv(gl.getUniformLocation(motionBlurYProgram, "textureHeight"),[height]); 
            gl.uniform1fv(gl.getUniformLocation(motionBlurYProgram, "size"), [size]);
            gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
            blurredB1A = createTextureFromCanvas(gl, webglCanvas);
            gl.deleteTexture(blurredMaskTexture);
      
            gl.useProgram(blurProgram);
            gl.enableVertexAttribArray(gl.getAttribLocation(blurProgram, "position"));
            gl.vertexAttribPointer(gl.getAttribLocation(blurProgram, "position"), 2, gl.FLOAT, false, 0, 0);
            gl.activeTexture(gl.TEXTURE0);
            gl.bindTexture(gl.TEXTURE_2D, imageTexture);
            gl.uniform1i(gl.getUniformLocation(blurProgram, "texture"), 0);
            gl.activeTexture(gl.TEXTURE1);
            gl.bindTexture(gl.TEXTURE_2D, maskTexture); 
            gl.uniform1i(gl.getUniformLocation(blurProgram, "maskTexture"), 1);
            gl.activeTexture(gl.TEXTURE2);
            gl.bindTexture(gl.TEXTURE_2D, blurredAlpha);
            gl.uniform1i(gl.getUniformLocation(blurProgram, "blurred_alpha"), 2);
            gl.activeTexture(gl.TEXTURE3);
            gl.bindTexture(gl.TEXTURE_2D, blurredFA);
            gl.uniform1i(gl.getUniformLocation(blurProgram, "blurred_FA"), 3);
            gl.activeTexture(gl.TEXTURE4);
            gl.bindTexture(gl.TEXTURE_2D, blurredB1A);
            gl.uniform1i(gl.getUniformLocation(blurProgram, "blurred_B1A"), 4);
            gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
      
            gl.deleteProgram(motionBlurXProgram);
            gl.deleteProgram(motionBlurYProgram);
            gl.deleteProgram(cutoffProgram);
            gl.deleteProgram(blurProgram);
            gl.deleteShader(vs);
            gl.deleteShader(hfs);
            gl.deleteShader(vfs);
            gl.deleteShader(cutoffShader);
            gl.deleteShader(blurShader);
            gl.deleteTexture(imageTexture);
            gl.deleteTexture(maskTexture);
            gl.deleteTexture(blurredAlpha);
            gl.deleteTexture(blurredFA);
            gl.deleteTexture(blurredB1A);
      
            null == (ctx = (result = createCanvas(width, height)).getContext("2d")) || ctx.drawImage(webglCanvas, 0, 0, width, height);
            gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
            gl.finish();
            null === (canvas = gl.getExtension("WEBGL_lose_context")) || (void 0 === canvas || canvas.loseContext());
            return result;
          }




      function renderImage(img, width, height, filename) {
        return new Promise((resolve) => {
          // const ctx = canvas.getContext('2d') //获取 canvas 绘图上下文
    
          // canvas.width = width
          // canvas.height = height
          // const img = new Image()
          img.onload = () => {
            // ctx.drawImage(img,0,0)
            resolve()
          }
          img.src = filename
        });
      }

      const urlParams = new URLSearchParams(window.location.search);
      const taskId = urlParams.get('taskId');
      const imagePath = urlParams.get('imagePath') || '/static/image.png';
      const maskPath = urlParams.get('maskPath') || '/static/mask.png';
      const imageWidth = urlParams.get('imageWidth') || 455;
      const imageHeight = urlParams.get('imageHeight') || 616;

      // const blendCanvas = document.getElementById('blend-canvas') //获取 canvas 组件
      // const blendCtx = blendCanvas.getContext('2d')
      // blendCanvas.width = imageWidth
      // blendCanvas.height = imageHeight

      const image = new Image()
      const mask = new Image()
      const promises = [
        renderImage(image, imageWidth, imageHeight, imagePath), 
        renderImage(mask, imageWidth, imageHeight, maskPath),
      ];
      Promise.all(promises).then((results) => {
        const blendCanvas = blendImage(imageWidth, imageHeight, image, mask)
        // blendCtx.drawImage(blendCanvas,0,0)
        console.log(taskId+'?::?'+blendCanvas.toDataURL("image/png", 1.0));
      }).catch((error) => {
        console.error(error);
      });
    }

      `,
  }}
/>
</div>)
}